package com.weshare.job;

import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import com.weshare.model.FileCustom;
import com.weshare.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Component
public class FileBackupJobDb implements SimpleJob {

    private final int FETCH_SIZE = 1;
    public static List<FileCustom> files = new ArrayList<FileCustom>();

    @Autowired
    private FileService fileService;

    public void execute(ShardingContext shardingContext) {

        // 作业分片信息
        int shardingItem = shardingContext.getShardingItem();
        System.out.println(String.format("作业分片：%d", shardingItem));
        //分片参数
        String jobParameter = shardingContext.getJobParameter();
        System.out.println(jobParameter);
        // 获取备份文件
        List<FileCustom> fileCustoms = fetehUnBackupFiles(jobParameter, FETCH_SIZE);
        // 备份文件
        backupFiles(fileCustoms);
    }

    /**
     * 备份文件
     *
     * @param files
     */
    private void backupFiles(List<FileCustom> files) {


        fileService.backupFiles(files);
    }

    /**
     * 获取备份文件
     *
     * @param count
     * @return
     */
    private List<FileCustom> fetehUnBackupFiles(String fileType, int count) {

        List<FileCustom> fileCustoms = fileService.fetchUnBackupFiles(fileType, count);
        System.out.printf("time:%s,获取文件%d个\n", LocalDateTime.now(), count);
        return fileCustoms;
    }
}
